<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import CustomNavbar from './components/CustomNavbar.vue'
import { ref } from "vue"
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import PageSkeleton from './components/PageSkeleton.vue'
import { useGuessList } from '@/composables'
// import type { XtxGuessInstance } from '@/types/component'

// 存储轮播图数据
const bannerList = ref<BannerItem[]>([])
// 存储分类、热门推荐数据
const categoryList = ref<CategoryItem[]>([])
const hotList = ref<HotItem[]>([])
// 控制下拉刷新状态
const isTriggered = ref(false)
// 控制骨架屏是否加载状态
const isLoading = ref(false)

// 获取轮播图数据
const getHomeBannerData = async () => {
    const res = await getHomeBannerAPI()
    bannerList.value = res.result
}

// 获取前台分类数据
const getHomeCategoryData = async () => {
    const res = await getHomeCategoryAPI()
    categoryList.value = res.result
}

// 获取热门推荐数据
const getHomeHotData = async () => {
    const res = await getHomeHotAPI()
    hotList.value = res.result
}

// 组件加载时调用(请求数据、骨架屏业务实现)
onLoad(async () => {
    isLoading.value = true
    await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotData()])
    isLoading.value = false
})


// // 获取子组件实例(用于滚动加载)
// const guessRef = ref<XtxGuessInstance>()
// // 滚动容器触底
// const onScrolltolower = () => {
//     guessRef.value?.getMore()
// }

// 直接调用猜你喜欢组合式函数
const { guessRef, onScrolltolower } = useGuessList()

// 下拉刷新时触发
const onRefresherrefresh = async () => {
    isTriggered.value = true  // 开始动画
    // 重置猜你喜欢组件数据
    guessRef.value?.resetData()
    // 加载数据(使用Promise.all同时请求数据减少等待时间)
    await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotData(), guessRef.value?.getMore()])
    isTriggered.value = false // 关闭动画
}
</script>

<template>
    <!-- 自定义导航栏 -->
    <CustomNavbar />
    <!-- 滚动容器 -->
    <scroll-view refresher-enabled @refresherrefresh="onRefresherrefresh" :refresher-triggered="isTriggered" scroll-y
        @scrolltolower="onScrolltolower" class="scroll-view">
        <!-- 骨架屏组件 -->
        <PageSkeleton v-if="isLoading" />
        <template v-else>
            <!-- 自定义轮播图 -->
            <XtxSwiper :list="bannerList" />
            <!-- 分类面板 -->
            <CategoryPanel :list="categoryList" />
            <!-- 热门推荐 -->
            <HotPanel :list="hotList" />
            <!-- 猜你喜欢 -->
            <XtxGuess ref="guessRef" />
        </template>
    </scroll-view>
</template>

<style lang="scss">
// APP端首屏滚动样式问题适配
/* #ifdef APP-PLUS */
#app,
/* #endif */
page {
    display: flex;
    flex-direction: column;
    height: 100%;
    background-color: #f7f7f7;
}

.scroll-view {
    flex: 1;
}
</style>
